package syncSingle;
/*
* 使用同步机制将单例模式中的懒汉式改写为线程安全的
*
* */
public class Single {
    public static void main(String[] args) {
        Bank b = Bank.getInstance();
        Bank c = Bank.getInstance();
        Bank d = Bank.getInstance();


    }

}

/*
* 懒汉式的单例模式
* */
class Bank{
    private Bank(){}

    private static Bank instance = null;

    //1:加上synchronized修饰,这个方法就是线程安全的,同步方法的锁就是类本身
//    public static synchronized Bank getInstance(){
    public static Bank getInstance(){

        //2:使用同步代码块的方式:效率稍差
//        synchronized (Bank.class){
//            if (instance == null){
//                instance = new Bank();
//            }
//            return instance;
//        }

//        3:效率更高
        if (instance == null){
            synchronized (Bank.class){
                if (instance == null){
                    instance = new Bank();
                }
                return instance;
            }
        }
        return instance;
    }
}